import { Injectable } from '@nestjs/common';
import { MissionLogEntity } from './mission-log.entity';
import { Between, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { MissionRecordDto } from '../mission.dto';
import { isNil } from 'lodash';
import dayjs from 'dayjs';
import { MissionType } from '../mission.model';
import { CommonStatus } from '~/common/entity/common.entity';

@Injectable()
export class MissionLogService {
  constructor(
    @InjectRepository(MissionLogEntity)
    private readonly missionLogRepository: Repository<MissionLogEntity>
  ) {}

  /**
   * 查询任务记录
   * @param dto 任务记录数据传输对象
   * @param userId 用户ID
   * @param tenantId 租户ID
   * @param missionId 任务ID
   * @return {Promise<boolean>} 是否已存在
   */
  async findOne(
    userId: number,
    missionId: number,
    missionType: MissionType,
    relatedId: string
  ): Promise<MissionLogEntity | null> {
    return await this.missionLogRepository.findOneBy({
      userId,
      missionId,
      missionType,
      relatedId,
    });
  }

  /**
   * 根据任务类型和相关ID查询任务记录
   * @param relatedId 关联ID
   * @param userId 用户ID
   * @param missionId 任务ID
   * @returns {Promise<number[]>} 返回任务记录的ID数组
   */
  async findByCatalog(diseaseId: number, userId: number): Promise<number[]> {
    const logs: Array<MissionLogEntity | null> = await this.missionLogRepository.findBy({
      userId,
      missionType: MissionType.CATALOG,
      diseaseId,
    });

    return logs.length ? logs.map((log: MissionLogEntity) => log.id) : [];
  }

  /**
   * 根据任务类型和相关ID查询任务记录
   * @param missionType 任务类型
   * @param relatedId 关联ID
   * @param userId 用户ID
   * @returns {Promise<MissionLogEntity[]>} 返回任务记录数组
   */
  async findCountByExamQuiz(
    missionType: MissionType,
    isPerpetual: CommonStatus,
    date: [string, string]
  ): Promise<number> {
    const whereCondition: any = {
      missionType,
    };

    // 如果不是永久，则添加时间范围条件
    if (isPerpetual === CommonStatus.NO && date && date.length === 2) {
      const startDate = new Date(date[0]);
      const endDate = new Date(date[1]);
      whereCondition.createdAt = Between(startDate, endDate);
    }

    return await this.missionLogRepository.count({
      where: whereCondition,
    });
  }

  /**
   * 创建任务记录
   * @param userId 用户ID
   * @param missionId 任务ID
   * @param missionType 任务类型
   * @param relatedId 关联ID（根据任务类型区分：CATALOG-目录ID，RECOMMEND-文章ID，EXAM-答卷ID，QNAIRE-问卷ID）
   * @returns {Promise<MissionLogEntity>} 创建的任务记录实体
   */
  async create(
    userId: number,
    missionId: number,
    missionType: MissionType,
    relatedId: string
  ): Promise<MissionLogEntity> {
    const existingLog = await this.findOne(userId, missionId, missionType, relatedId);

    if (!isNil(existingLog)) {
      return existingLog; // 如果记录已存在，直接返回
    }

    const newLog = this.missionLogRepository.create({
      userId,
      missionId,
      isFinished: CommonStatus.YES, // 默认设置为已完成
      missionType,
      relatedId,
    });

    return await this.missionLogRepository.save(newLog);
  }

  /**
   * 根据任务记录ID删除任务记录
   * @param id 任务记录ID
   * @returns {Promise<void>} 无返回值
   */
  async createByExamQuiz(
    userId: number,
    missionId: number,
    missionType: MissionType,
    relatedId: string
  ): Promise<MissionLogEntity> {
    const newLog = this.missionLogRepository.create({
      userId,
      missionId,
      isFinished: CommonStatus.YES, // 默认设置为已完成
      missionType,
      relatedId,
    });

    return await this.missionLogRepository.save(newLog);
  }

  /**
   * 获取今日或昨日任务完成总数
   * @returns 今日或昨日任务完成总数
   */
  async getTodayOrLastdayTaskCount(): Promise<[number, number]> {
    const todayStart = new Date(dayjs().format('YYYY-MM-DD 00:00:00'));
    const todayEnd = new Date(dayjs().add(1, 'day').format('YYYY-MM-DD 00:00:00'));
    const yesterdayStart = new Date(dayjs().subtract(1, 'day').format('YYYY-MM-DD 00:00:00'));
    const yesterdayEnd = new Date(dayjs().format('YYYY-MM-DD 00:00:00'));

    const todayCount = await this.missionLogRepository.count({
      where: {
        createdAt: Between(todayStart, todayEnd),
      },
    });

    const yesterdayCount = await this.missionLogRepository.count({
      where: {
        createdAt: Between(yesterdayStart, yesterdayEnd),
      },
    });

    return [todayCount, yesterdayCount];
  }

  /**
   * 获取用户的任务完成统计
   * @param userId 用户ID
   * @returns [今日任务完成数, 总任务完成数]
   */
  async getUserTaskCount(userId: number): Promise<[number, number]> {
    const todayStart = new Date(dayjs().format('YYYY-MM-DD 00:00:00'));
    const todayEnd = new Date(dayjs().add(1, 'day').format('YYYY-MM-DD 00:00:00'));

    // 查询今日任务完成数
    const todayCount = await this.missionLogRepository.count({
      where: {
        userId,
        createdAt: Between(todayStart, todayEnd),
      },
    });

    // 查询总任务完成数
    const totalCount = await this.missionLogRepository.count({
      where: {
        userId,
      },
    });

    return [todayCount, totalCount];
  }
}
